import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { authApi } from "@/api/auth";
import type {
  UserInfo,
  UserAbilities,
  UserAchievement,
  UserTier,
  UserStatistics,
  LoginCredentials,
  RegisterData,
} from "@/types";

export const useUserStore = defineStore("user", () => {
  // 状态
  const userInfo = ref<UserInfo | null>(null);
  const isAuthenticated = ref(false);
  const userAbilities = ref<UserAbilities | null>(null);
  const userAchievements = ref<UserAchievement[]>([]);
  const userTier = ref<UserTier | null>(null);
  const userStatistics = ref<UserStatistics | null>(null);
  const loading = ref(false);

  // 计算属性
  const hasCompletedAssessment = computed(() => {
    return userAbilities.value?.isBaseline === true;
  });

  const currentTierName = computed(() => {
    return userTier.value?.displayName || "Social Seed";
  });

  const isLoggedIn = computed(() => {
    return isAuthenticated.value && userInfo.value !== null;
  });

  // 方法
  async function login(credentials: LoginCredentials) {
    try {
      loading.value = true;
      const response = await authApi.login(credentials);

      // 转换API返回的User数据到UserInfo格式
      const apiUser = response.data.user;
      userInfo.value = {
        id: apiUser.id,
        username: apiUser.username,
        email: apiUser.email,
        avatar: apiUser.avatar_url,
        createdAt: apiUser.created_at,
        updatedAt: apiUser.created_at, // 如果没有updated_at，使用created_at
      };
      isAuthenticated.value = true;

      // 保存token和用户信息到本地存储
      localStorage.setItem("token", response.data.access_token);
      localStorage.setItem("user", JSON.stringify(userInfo.value));

      return response;
    } catch (error) {
      console.error("Login failed:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  }

  async function register(userData: RegisterData) {
    try {
      loading.value = true;
      // 转换RegisterData到RegisterParams格式
      const registerParams = {
        username: userData.username,
        email: userData.email,
        password: userData.password,
        password_confirmation: userData.password_confirmation,
        agreeToTerms: userData.agreeToTerms,
      };
      const response = await authApi.register(registerParams);

      // 转换API返回的User数据到UserInfo格式
      const apiUser = response.data.user;
      userInfo.value = {
        id: apiUser.id,
        username: apiUser.username,
        email: apiUser.email,
        avatar: apiUser.avatar_url,
        createdAt: apiUser.created_at,
        updatedAt: apiUser.created_at, // 如果没有updated_at，使用created_at
      };
      isAuthenticated.value = true;

      // 保存token和用户信息到本地存储
      localStorage.setItem("token", response.data.access_token);
      localStorage.setItem("user", JSON.stringify(userInfo.value));

      return response;
    } catch (error) {
      console.error("Registration failed:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  }

  async function logout() {
    try {
      await authApi.logout();
    } catch (error) {
      console.error("Logout API call failed:", error);
    } finally {
      // 清除本地状态和存储
      userInfo.value = null;
      isAuthenticated.value = false;
      userAbilities.value = null;
      userAchievements.value = [];
      userTier.value = null;
      userStatistics.value = null;

      localStorage.removeItem("token");
      localStorage.removeItem("user");
    }
  }

  // 初始化用户状态（从本地存储恢复）
  function initializeFromStorage() {
    const token = localStorage.getItem("token");
    const userStr = localStorage.getItem("user");

    if (token && userStr) {
      try {
        const user = JSON.parse(userStr);
        userInfo.value = user;
        isAuthenticated.value = true;
      } catch (error) {
        console.error("Failed to parse user data from localStorage:", error);
        // 清除无效的本地存储
        localStorage.removeItem("token");
        localStorage.removeItem("user");
      }
    }
  }

  // 从服务器刷新用户信息
  async function refreshUserInfo() {
    if (!isAuthenticated.value) return;

    try {
      loading.value = true;
      const response = await authApi.getCurrentUser();

      if (response.success && response.data) {
        const apiUser = response.data;
        userInfo.value = {
          id: apiUser.id,
          username: apiUser.username,
          email: apiUser.email,
          avatar: apiUser.avatar_url,
          createdAt: apiUser.created_at,
          updatedAt: apiUser.updated_at || apiUser.created_at,
        };

        // 更新本地存储
        localStorage.setItem("user", JSON.stringify(userInfo.value));
      }
    } catch (error) {
      console.error("Failed to refresh user info:", error);
    } finally {
      loading.value = false;
    }
  }

  // 更新用户头像
  function updateAvatar(avatarUrl: string) {
    if (userInfo.value) {
      userInfo.value.avatar = avatarUrl;
      // 更新本地存储
      localStorage.setItem("user", JSON.stringify(userInfo.value));
    }
  }

  // 更新用户信息
  function updateUserInfo(updates: Partial<UserInfo>) {
    if (userInfo.value) {
      Object.assign(userInfo.value, updates);
      // 更新本地存储
      localStorage.setItem("user", JSON.stringify(userInfo.value));
    }
  }

  return {
    // 状态
    userInfo,
    isAuthenticated,
    userAbilities,
    userAchievements,
    userTier,
    userStatistics,
    loading,

    // 计算属性
    hasCompletedAssessment,
    currentTierName,
    isLoggedIn,

    // 方法
    login,
    register,
    logout,
    initializeFromStorage,
    refreshUserInfo,
    updateAvatar,
    updateUserInfo,
  };
});
